<html>
<script>

  function success_() {
    domAutomationController.send(true);
  }

  function failure_() {
    domAutomationController.send(false);
  }

  // EME creates session IDs dynamically, so we have no idea what it will be.
  // As the tests only need to create a single session, keep track of the
  // last session ID created.
  var savedSessionId = 'UnknownSessionId';

  function createPersistentSession() {
    // This function creates a persistent-license type session, and resolves
    // with the created session object on success.
    return navigator.requestMediaKeySystemAccess(
      'org.chromium.externalclearkey', [{
        initDataTypes: ['keyids'],
        audioCapabilities: [
          // Include a set of codecs that should cover all user agents.
          {contentType: 'audio/mp4; codecs="mp4a.40.2"'},
          {contentType: 'audio/webm; codecs="opus"'}
        ],
        persistentState: 'required',
        sessionTypes: ['persistent-license'],
      }])
    .then(function(access) {
      return access.createMediaKeys();
    })
    .then(function(mediaKeys) {
      return mediaKeys.createSession('persistent-license');
    });
  }

  function handleMessageEvent(e) {
    var session = e.target;
    var te = new TextEncoder();
    var license = te.encode(
      '{"keys":[{"kty":"oct","k":"tQ0bJVWb6b0KPL6KtZIy_A","kid":"LwVHf8JLtPrv2GUXFW2v_A"}],"type":"persistent-license"}');

    savedSessionId = session.sessionId;
    session.update(license).then(success_, failure_);
  }

  function setMediaLicense() {
    var te = new TextEncoder();
    var initData = te.encode('{"kids":["LwVHf8JLtPrv2GUXFW2v_A"]}');

    createPersistentSession().then(function(session) {
      // generateRequest() will trigger a 'message' event, which we need to
      // wait for in order to call update() which provides the license.
      session.addEventListener('message', handleMessageEvent, false);
      return session.generateRequest('keyids', initData);
    })
    // Success is reported from handleMessageEvent().
    .catch(failure_);
  }

  function hasMediaLicense() {
    createPersistentSession().then(function(session) {
      return session.load(savedSessionId);
    })
    .then(function(result) {
      // |result| is a boolean, indicating if the session was loaded or not.
      domAutomationController.send(result);
    })
    .catch(failure_);
  }
</script>

<body>
  This page is used to test creation and deletion of Media Licenses.
  The functions are called from BrowsingDataRemoverBrowserTest::HasDataForType
  and BrowsingDataRemoverBrowserTest::SetDataForType.
</body>

</html>